<?php

namespace app\admin\controller\wanlshop;

use app\common\controller\Backend;
use fast\Tree;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 商品、文章类目管理
 *
 * @icon fa fa-circle-o
 */
class Category extends Backend
{
    
    /**
     * Category模型对象
     * @var \app\admin\model\wanlshop\Category
     */
    protected $model = null;
    protected $tree = null;
    protected $channelList=[];
    //关于分类Category的缓存，本项目中有如下缓存key
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\wanlshop\Category;
        $this->tree = Tree::instance();
		$type = $this->request->request("type");
		// 1.1.9升级 排序方式
        //分类
        $cacheKey=$this->model->cacheKey['channelList_category'];
        $channelList=cache($cacheKey);
        if(!$channelList) {
            if ($type) {
                $this->tree->init(collection($this->model->where('type', $type)->order('weigh asc,id asc')->select())->toArray(), 'pid');
            } else {
                $this->tree->init(collection($this->model->order('weigh asc,id asc')->select())->toArray(), 'pid');
            }
            $channelList = $this->tree->getTreeList($this->tree->getTreeArray(0), 'name');
            cache($cacheKey,$channelList);
        }
		$this->channelList =$channelList;
		$this->view->assign("type", $type);
		$this->view->assign("channelList", $this->channelList);
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("flagList", $this->model->getFlagList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }
    
    /**
     * 查看
     */
	public function index()
	{
	    if ($this->request->isAjax()) {
			$list = $this->channelList;
	        $list = array_values($list);
	        $total = count($list);
	        $result = array("total" => $total, "rows" => $list);
	        return json($result);
	    }
	    return $this->view->fetch();
	}
	
	// 商品
	public function goods()
	{
	    if ($this->request->isAjax()) {
	        $list = [];
	        foreach ($this->channelList as $item) {
	            if ($item['type'] == 'goods') {
	                $item['channel'] = $this->tree->getChildrenIds($item['id'], true);
	                $list[] = $item;
	            }
	        }
	        $list = array_values($list);
	        $total = count($list);
	        $result = array("total" => $total, "rows" => $list);
	        return json($result);
	    }
        //全境供应链云-获取分类
        $result=loadCategorysFromApi(0);
        if(isset($result['code'])) $this->error($result['msg']);
	    return $this->view->fetch();
	}


	/**
	 * 选择链接
	 */
	public function select()
	{
	    if ($this->request->isAjax()) {
	        return $this->goods();
	    }
	    return $this->view->fetch();
	}
	
	
	// 文章
	public function article()
	{
	    if ($this->request->isAjax()) {
	        $list =collection($this->model->where('type','article')->select())->toArray();
	        $list = array_values($list);
	        $total = count($list);
	        $result = array("total" => $total, "rows" => $list);
	        return json($result);
	    }
	    return $this->view->fetch();
	}
	
	/**
	 * 生成菜单
	 *
	 * @internal
	 */
	public function create()
	{
		if ($this->request->isPost()) {
			$params = $this->request->post("row/a");
			$list = [];
			foreach(explode("\r\n", $params['name']) as $name){
				$list[] = [
					'pid' => $params['pid'],
					'type' => 'goods',
					'isnav' => 1,
					'name' => $name,
					'image' => '/uploads/category/category_'.\fast\Pinyin::get($name).'3x.jpg'
				];
			}
            $this->model->clearCategoryCache();
			// 生成菜单
			if ($this->model->saveAll($list) !== false) {
			    $this->success('一键批量生成类目成功！');
			} else {
			    $this->error(__('No rows were inserted'));
			}
		}
		return $this->view->fetch();
	}


    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['id']=$this->generate_newid();
            $params['local']=1;
            $this->model->create($params);
            $this->model->clearCategoryCache();
            $this->success('保存成功');
        }
        return $this->view->fetch();
    }


    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            //全境供应链云-获取分类
            if(!$row['local'] && $row['type'] == 'goods') {
                $data = loadCategorysFromApi($ids, true);//查询二级类目
                if(isset($data['code'])) $this->error($data['msg']);
                if ($data) {
                    foreach ($data as $item) {
                        $subData = loadCategorysFromApi($item['id'], true);//查询三级类目
                        if(isset($subData['code'])) $this->error($subData['msg']);
                        $data = array_merge($data, $subData);
                    }
                    $this->model->saveAll($data, false);
                }
            }
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->model->clearCategoryCache();
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    /**
     * 删除
     */
    public function del($ids = ""){
        $this->model->clearCategoryCache();
        parent::del($ids);
        $category=$this->model->get($ids);
        if(!$category['local'] && $category['type']=='goods') {
            $sub_ids = $this->model->where('pid', $ids)->column('id');
            if ($sub_ids) {
                array_merge($sub_ids, $this->model->where('pid', 'in', $sub_ids)->column('id'));
            }
            $this->model->whereIn('id',$sub_ids)->delete();
        }
        $this->success();
    }

	
	/**
	 * Selectpage搜索
	 *
	 * @internal
	 */
	public function selectpage()
	{
	    return parent::selectpage();
	}
}